﻿<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class VerifyLogin extends CI_Controller {

	function __construct()
	{
		parent::__construct();
		$this->load->model('user','',TRUE);
		//$this->load->library('passwordHelper');
	}

	function index()
	{
		
		//This method will have the credentials validation
		$this->load->library('form_validation');

		$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
		
		// Set custom validation message
		$this->form_validation->set_message('required','%s không được để trống!');

		if($this->form_validation->run() == FALSE)
		{
			//Field validation failed.  User redirected to login page
			$this->load->view('login');
		}
		else
		{
			//Go to private area
			redirect('tdc', 'refresh');
		}
	}

	function check_database($password)
	{			
		//Field validation succeeded.  Validate against database
		$username = $this->input->post('username');

		//query the database
		$result = $this->user->get_user($username);

		if($result)
		{		
			$sess_array = array();
			if (crypt($password . $result->salt, $result->password) == $result->password)
			{
				date_default_timezone_set('Asia/Ho_Chi_Minh');
				$sess_array = array(
					'user_id' => $result->user_id,
					'username' => $result->username,
					'current_login_time' => date("Y/m/d H:i:s", time())
				);
				$this->session->set_userdata('logged_in', $sess_array);
				return TRUE;
			}
		}
		else
		{
			$this->form_validation->set_message('check_database', 'Tên đăng nhập hoặc mật khẩu không đúng!');
			return false;
		}
	}
}
?>